package com.fourool.goodsmall.service.impl;

import com.fourool.goodsmall.common.Result;
import com.fourool.goodsmall.dto.*;
import com.fourool.goodsmall.entity.*;
import com.fourool.goodsmall.mapper.*;
import com.fourool.goodsmall.service.GOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

@Service
public class GOrderServiceImpl implements GOrderService {

    @Autowired private GOrderMapper orderMapper;
    @Autowired private GPersonMapper personMapper;
    @Autowired private GGoodsMapper goodsMapper;
    @Autowired private GAddressMapper addressMapper;

    @Override
    @Transactional
    public Result createOrder(CreateOrderDTO dto) {
        // 1. 校验数据
        GPerson person = personMapper.findById(dto.getPid());
        if (person == null) return Result.error(404, "用户不存在");
        GGoods goods = goodsMapper.findById(dto.getGid());
        if (goods == null) return Result.error(404, "商品不存在");
        GAddress address = addressMapper.findById(dto.getAid());
        if (address == null || address.getStatus() == 0 || !address.getPid().equals(dto.getPid())) {
            return Result.error(404, "收货地址无效");
        }

        // 2. 生成订单号 (时间戳 + 随机数)
        String orderNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) +
                ThreadLocalRandom.current().nextInt(100, 1000);

        // 3. 创建订单对象
        GOrder order = new GOrder();
        order.setOrderNo(orderNo);
        order.setPid(dto.getPid());
        order.setGid(dto.getGid());
        order.setAid(dto.getAid());
        order.setTotalAmount(goods.getPrice()); // 订单金额等于商品价格
        order.setStatus(0); // 待支付

        // 4. 插入数据库
        orderMapper.insert(order);

        // 5. 返回新订单的ID和订单号
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("orderId", order.getId());
        resultData.put("orderNo", order.getOrderNo());
        return Result.success(resultData);
    }

    @Override
    public Result getOrderList(Integer pid, Integer status) {
        return Result.success(orderMapper.findOrderListByPid(pid, status));
    }

    @Override
    public Result getOrderDetail(Integer id) {
        GOrder order = orderMapper.findById(id);
        if (order == null) return Result.error(404, "订单不存在");

        // 组装详情数据
        Map<String, Object> detail = new HashMap<>();
        detail.put("orderInfo", order);
        detail.put("goodsInfo", goodsMapper.findById(order.getGid()));
        detail.put("addressInfo", addressMapper.findById(order.getAid()));

        return Result.success(detail);
    }

    @Override
    @Transactional
    public Result payOrder(OrderPayDTO dto) {
        // 1. 校验订单和用户
        GOrder order = orderMapper.findById(dto.getOrderId());
        if (order == null || !order.getPid().equals(dto.getPid())) {
            return Result.error(404, "订单不存在或无权操作");
        }
        if (order.getStatus() != 0) {
            return Result.error(400, "订单状态异常，无法支付");
        }
        GPerson person = personMapper.findById(dto.getPid());

        // 2. 检查积分是否足够
        BigDecimal userRecord = new BigDecimal(person.getRecord());
        if (userRecord.compareTo(order.getTotalAmount()) < 0) {
            return Result.error(400, "积分不足");
        }

        // 3. 扣除用户积分
        int remainingRecord = userRecord.subtract(order.getTotalAmount()).intValue();
        GPerson updatedPerson = new GPerson();
        updatedPerson.setId(person.getId());
        updatedPerson.setRecord(remainingRecord); // 更新积分字段
        personMapper.updateRecord(updatedPerson);

        // 4. 更新订单状态
        order.setStatus(1); // 待发货
        order.setPayTime(new Date());
        orderMapper.update(order);

        return Result.success("支付成功");
    }

    @Override
    public Result cancelOrder(Integer id) {
        GOrder order = orderMapper.findById(id);
        if (order == null) return Result.error(404, "订单不存在");

        // 只有待支付的订单可以取消
        if (order.getStatus() != 0) {
            return Result.error(400, "此订单状态无法取消");
        }

        order.setStatus(4); // 已取消
        orderMapper.update(order);
        return Result.success("订单已取消");
    }
}